#include "clienthandelr.h"
#include "dbhelper.h"
#include"servermanager.h"
#include "meetingmanager.h"

clientHandelr::clientHandelr(QTcpSocket *socket, QObject *parent) : QObject(parent)
{
    this->socket = socket;
    connect(this->socket,&QTcpSocket::readyRead,this,&clientHandelr::onReadyRead);
}

void clientHandelr::registHanler(MessagePackage &pack)
{
    QString name = pack.userName();
    QString pswd = pack.userPswd();
    bool ret = dbhelper::getInstance()->userRegist(name,pswd);
    pack.setResult(ret);

    MessagePackage::sendMessage(pack,socket);
}

void clientHandelr::loginHanler(MessagePackage &pack)
{
    QString name = pack.userName();
    QString pswd = pack.userPswd();
    bool ret = dbhelper::getInstance()->userLogin(name,pswd);
    pack.setResult(ret);
    MessagePackage::sendMessage(pack,socket);
    if(ret)//注释掉在线列表获取错误的地方
    {
        emit this->new_onlUser(name,socket);
    }
}
void clientHandelr::setServerManager(QObject* server) {
    this->server = server;
}
void clientHandelr::quitHanler(MessagePackage &pack)
{
    QString name = pack.userName();
    dbhelper::getInstance()->setOnlineStatus(name,0);
    qDebug()<<name<<"下线";
    emit this->update_onl();
    emit this->onl_userOff(name);//在线列表错误获取方式
}


void clientHandelr::onReadyRead()
{
    while(socket->bytesAvailable() > 0)
    {
        MessagePackage pack;
        MessagePackage::recvMessage(pack,socket);
        if(pack.type() == "regist")
        {
            registHanler(pack);
        }
        else if(pack.type() == "login")
        {
            loginHanler(pack);
        }
        else if(pack.type() == "quit")
        {
            quitHanler(pack);
        }
        else if(pack.type() == "update")
        {
            emit this->client_upList(this->socket);
        }
        else if(pack.type() == "single")
        {
            emit this->singleMessage(pack);
        }
        else if(pack.type() == "group_create")
        {
            groupCreateHandler(pack);
        }
        else if(pack.type() == "group_message")
        {
            groupMessageHandler(pack);
        }
        else if(pack.type() == "group_list")
        {
            groupListHandler(pack);
        }
        else if(pack.type() == "group_join")
        {
            groupJoinHandler(pack);
        }
        // 文件 相关
        else if(pack.type() == "file_upload")
        {
            // 保存文件到服务器目录
            QDir().mkdir("server_files");
            QFile file("server_files/"+pack.groupName());
            if(file.open(QIODevice::WriteOnly))
            {
                //qDebug()<<"能够写文件";
                file.write(QByteArray::fromBase64(pack.getMessage().toLatin1()));
                file.close();

                // 返回确认
                MessagePackage resp;
                resp.setType("file_upload_ok");
                MessagePackage::sendMessage(resp, this->socket);
            }
        }
        else if (pack.type() == "file_list_req")
        {
            emit clcFile();
            // 1. 生成文件列表数据
            QDir dir("server_files");
            QJsonArray files;
            foreach (QFileInfo fi, dir.entryInfoList(QDir::Files)) {
                QJsonObject fileObj;
                fileObj["name"] = fi.fileName();
                fileObj["size"] = fi.size();
                files.append(fileObj);
                QString  filename=fi.fileName()+"   "+QString::number(fi.size())+"kb";
                emit setFile(filename);
            }
            // 2. 构造完整消息对象
            QJsonObject rootObj;
            rootObj["type"] = "file_list";  // 设置消息类型
            rootObj["data"] = files;        // 附加文件数组
            // 3. 发送消息
            // 服务器端修正
            MessagePackage resp;
            resp.setType("file_list");
            resp.setData(QJsonDocument(rootObj).toJson());
            MessagePackage::sendMessage(resp, this->socket);
            qDebug() << "[Server] 已发送文件列表：" << QJsonDocument(rootObj).toJson();
        }
        else if (pack.type() == "file_download")
        {
            QString filename = pack.groupName();
            QString savePath = pack.getMessage(); // 获取客户端传递的保存路径

            QFile file("server_files/" + filename);
            if (file.open(QIODevice::ReadOnly))
            {
                MessagePackage resp;
                resp.setType("file_data");
                resp.setGroupName(savePath); // 将保存路径作为 groupName 传回
                resp.setMessage(file.readAll().toBase64());
                MessagePackage::sendMessage(resp, this->socket);
            }
        }
        else if(pack.type() == "create_meeting")
        {
            //qDebug()<<"能收到创建会议 请求";
            createMeetingHandler(pack);
        }
        else if(pack.type() == "join_meeting")
        {
            joinMeetingHandler(pack);
        }
    }
}

void clientHandelr::groupCreateHandler(MessagePackage &pack) {
    //qDebug()<<pack.groupName()<<pack.userName()<<pack.memberList();
    auto manager = qobject_cast<serverManager*>(server);
    if (!manager) return;

    QString groupId = dbhelper::getInstance()->createGroup(
        pack.groupName(),
        pack.userName()
    );

    if (!groupId.isEmpty()) {
        // 1. 添加所有成员（包含创建者）
        QStringList members = pack.memberList();
        members << pack.userName(); // 确保包含创建者

        // 2. 添加成员到数据库并发送刷新指令
        for ( QString &member : members) {
            if (dbhelper::getInstance()->addGroupMember(groupId, member)) {
                if (manager->isUserOnline(member)) {
                    // 发送强制刷新指令
                    MessagePackage refreshPack;
                    refreshPack.setType("force_refresh");
                    MessagePackage::sendMessage(refreshPack, manager->getUserSocket(member));
                    qDebug()<<"添加"<<member<<"成功";
                }
            }
        }

        // 3. 返回创建成功响应
        MessagePackage response;
        response.setType("group_create_resp");
        response.setResult(true);
        response.setGroupId(groupId);
        response.setGroupName(pack.groupName());
        MessagePackage::sendMessage(response, socket);
    } else {
        qDebug()<<"创建 失败";
    }
}

void clientHandelr::groupMessageHandler(MessagePackage &pack)
{
    auto manager = qobject_cast<serverManager*>(server);// 类型转换
    if(!manager) return;

    QString groupId = pack.groupId();
//    QString sender = pack.userName();



//    if(dbhelper::getInstance()->isGroupMember(groupId, sender)) {
        QJsonArray members = dbhelper::getInstance()->getGroupMembers(groupId);

        for(const auto &member : members) {
            QString memberName = member.toString();
            if(manager->isUserOnline(memberName)) {
                QTcpSocket *memberSocket = manager->getUserSocket(memberName);
                MessagePackage::sendMessage(pack, memberSocket);
            }
        }
//    }
}

void clientHandelr::groupListHandler(MessagePackage &pack)
{
    QString username = pack.userName();
    QJsonArray groups = dbhelper::getInstance()->getGroupList(username);



    MessagePackage response;
    response.setType("group_list_resp");
    response.setUserName(username);

    QJsonObject data;
    data["groups"] = groups;
    response.setData(QJsonDocument(data).toJson());
    //qDebug()<<"组列表"<<data["groups"].toArray();

    MessagePackage::sendMessage(response, socket);
    //qDebug()<<"发送列表"<<response.getData();


    //测试
    response.setType("test");
    MessagePackage::sendMessage(response, socket);
}

void clientHandelr::groupJoinHandler(MessagePackage &pack)
{
    auto manager = qobject_cast<serverManager*>(server);// 类型转换
    if(!manager) return;
    QString groupId = pack.groupId();
    QString username = pack.userName();

    bool success = dbhelper::getInstance()->addGroupMember(groupId, username);

    MessagePackage response;
    response.setType("group_join_resp");
    response.setResult(success);
    response.setGroupId(groupId);

    if(success) {
        response.setGroupName(dbhelper::getInstance()->getGroupName(groupId));

        // 通知群成员有新成员加入
        QJsonArray members = dbhelper::getInstance()->getGroupMembers(groupId);
        for(const auto &member : members) {
            QString memberName = member.toString();
            if(manager->isUserOnline(memberName) && memberName != username) {
                MessagePackage notify;
                notify.setType("group_member_added");
                notify.setGroupId(groupId);
                notify.setUserName(username);
                QTcpSocket *memberSocket = manager->getUserSocket(memberName);
                MessagePackage::sendMessage(notify, memberSocket);
            }
        }
    }

    MessagePackage::sendMessage(response, socket);
}
void clientHandelr::createMeetingHandler(MessagePackage &pack)
{
    Q_UNUSED(pack);
    QString meetingId = MeetingManager::instance()->createMeeting();
    Meeting meeting = MeetingManager::instance()->getMeetingInfo(meetingId);

    MessagePackage resp;
    resp.setType("meeting_created");
    resp.setMeetingId(meeting.id);
    resp.setMulticastIp(meeting.multicastIp);
    resp.setMulticastPort(meeting.multicastPort);
    MessagePackage::sendMessage(resp, socket);
    QString video=QString::number(++meetingnum)+"号会议:  "+meetingId;
    emit setVideoList(video);
}
void clientHandelr::joinMeetingHandler(MessagePackage &pack)
{
    QString meetingId = pack.meetingId();
    QString username = pack.userName();

    if(MeetingManager::instance()->joinMeeting(meetingId, username))
    {
        Meeting meeting = MeetingManager::instance()->getMeetingInfo(meetingId);

        MessagePackage resp;
        resp.setType("meeting_joined");
        resp.setMeetingId(meeting.id);
        resp.setMulticastIp(meeting.multicastIp);
        resp.setMulticastPort(meeting.multicastPort);
        MessagePackage::sendMessage(resp, socket);
    }
}
